package team.bluepen.order.web.servlet;

import team.bluepen.order.data.hdfs.HdfsManager;
import team.bluepen.order.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.stringtemplate.v4.misc.Misc.getFileName;

/**
 * @author Kai
 */
@WebServlet(name = "HdfsDownloadServlet", urlPatterns = "/api/hdfs/download")
public class HdfsDownloadServlet extends BaseServlet {
    public static final String PATH_PARAM = "path";

    @Override
    protected void post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getParameter(PATH_PARAM);
        if (StringUtil.isEmpty(path)) {
            return;
        }
        String downloadName = getFileName(path);
        resp.setContentType("text/text;charset=utf-8");
        resp.setContentType("application/x-msdownload;charset=UTF-8");
        resp.setHeader("Content-Disposition", "attachment; filename=" + downloadName);
        ServletOutputStream stream = resp.getOutputStream();
        HdfsManager.getInstance().download(path, stream);

        stream.close();
        resp.sendRedirect("/");
    }
}
